package com.farm.project.service.impl;

import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectGradationTasktype;
import com.farm.project.domain.ProjectType;
import com.farm.project.domain.ProjectTypeGradation;
import com.farm.project.domain.TaskType;
import com.farm.core.time.TimeTool;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.farm.project.dao.ProjectGradationDaoInter;
import com.farm.project.dao.ProjectGradationTasktypeDaoInter;
import com.farm.project.dao.ProjectTypeDaoInter;
import com.farm.project.dao.ProjectTypeGradationDaoInter;
import com.farm.project.dao.TaskTypeDaoInter;
import com.farm.project.service.ProjectGradationServiceInter;
import com.sun.star.uno.RuntimeException;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：项目阶段服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class ProjectGradationServiceImpl implements ProjectGradationServiceInter {
	@Resource
	private ProjectTypeDaoInter projecttypeDaoImpl;
	@Resource
	private ProjectGradationDaoInter projectgradationDaoImpl;
	@Resource
	private ProjectGradationTasktypeDaoInter projectgradationtasktypeDaoImpl;
	@Resource
	private ProjectTypeGradationDaoInter projecttypegradationDaoImpl;
	@Resource
	private TaskTypeDaoInter tasktypeDaoImpl;
	private static final Logger log = Logger.getLogger(ProjectGradationServiceImpl.class);

	@Override
	@Transactional
	public ProjectGradation insertProjectgradationEntity(ProjectGradation entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		entity.setUuid("NONE");
		if (StringUtils.isBlank(entity.getParentid())) {
			entity.setParentid("NONE");
		}
		entity.setTreecode("NONE");
		entity = projectgradationDaoImpl.insertEntity(entity);
		initTreeCode(entity.getId());
		entity.setUuid(entity.getId());
		projectgradationDaoImpl.editEntity(entity);
		return entity;
	}

	private void initTreeCode(String treeNodeId) {
		ProjectGradation node = getProjectgradationEntity(treeNodeId);
		if (node.getParentid().equals("NONE")) {
			node.setTreecode(node.getId());
		} else {
			node.setTreecode(projectgradationDaoImpl.getEntity(node.getParentid()).getTreecode() + node.getId());
		}
		projectgradationDaoImpl.editEntity(node);
	}

	@Override
	@Transactional
	public ProjectGradation editProjectgradationEntity(ProjectGradation entity, LoginUser user) {
		ProjectGradation entity2 = projectgradationDaoImpl.getEntity(entity.getId());
		entity2.setName(entity.getName());
		entity2.setSort(entity.getSort());
		entity2.setPcontent(entity.getPcontent());
		entity2.setPstate(entity.getPstate());
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		projectgradationDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteProjectgradationEntity(String id, LoginUser user) {
		if (projectgradationDaoImpl.selectEntitys(DBRule.addRule(new ArrayList<DBRule>(), "parentid", id, "="))
				.size() > 0) {
			throw new RuntimeException("不能删除该节点，请先删除其子节点");
		}
		ProjectGradation gradation = projectgradationDaoImpl.getEntity(id);
		if (gradation.getUuid().equals(gradation.getId())) {
			gradation.setPstate("2");
			gradation.setEtime(TimeTool.getTimeDate14());
			gradation.setEuser(user.getId());
			projectgradationDaoImpl.editEntity(gradation);
		} else {
			projectgradationDaoImpl.deleteEntity(gradation);
		}
	}

	@Override
	@Transactional
	public ProjectGradation getProjectgradationEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return projectgradationDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createProjectgradationSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query,
				"( SELECT ID, NAME, SORT,PARENTID, MODEL, MODEL AS MODELVAL, PCONTENT, PSTATE, EUSER, CUSER, ETIME, CTIME, UUID, ( SELECT COUNT(*) FROM PLOGS_RE_GRADATIONTASKTYPE WHERE PLOGS_RE_GRADATIONTASKTYPE.GRADATIONID = PLOGS_PROJECT_GRADATION.ID ) AS TASKTYPENUM FROM PLOGS_PROJECT_GRADATION  ) A",
				"ID,SORT,NAME ,MODEL,MODELVAL,PCONTENT,PSTATE,TASKTYPENUM");
		return dbQuery;
	}

	@Override
	@Transactional
	public DataQuery createGradationChooseQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "PLOGS_PROJECT_GRADATION",
				"ID, NAME, SORT,PARENTID, MODEL, MODEL AS MODELVAL, PCONTENT, PSTATE, EUSER, CUSER, ETIME, CTIME, UUID");
		return dbQuery;
	}

	@Override
	@Transactional
	public DataQuery createReTaskTypeQuery(DataQuery query, String gradationId) {
		DataQuery dbQuery = DataQuery.init(query,
				"PLOGS_RE_GRADATIONTASKTYPE a left join PLOGS_TASK_TYPE b on b.ID=a.TASKTYPEID",
				"A.ID AS ID,B.NAME AS NAME,A.SORT AS SORT,B.PCONTENT AS PCONTENT,B.PSTATE as PSTATE");
		return dbQuery;
	}

	@Override
	@Transactional
	public void editSort(String id, int sort, LoginUser currentUser) {
		ProjectGradation entity2 = projectgradationDaoImpl.getEntity(id);
		entity2.setSort(sort);
		projectgradationDaoImpl.editEntity(entity2);
	}

	@Override
	@Transactional
	public void bindTaskType(String tasktypeid, String gradationid, LoginUser currentUser) {
		projectgradationtasktypeDaoImpl
				.deleteEntitys(DBRuleList.getInstance().add(new DBRule("GRADATIONID", gradationid, "="))
						.add(new DBRule("TASKTYPEID", tasktypeid, "=")).toList());
		ProjectGradationTasktype entity = new ProjectGradationTasktype();
		entity.setGradationid(gradationid);
		entity.setTasktypeid(tasktypeid);
		entity.setSort(0);
		projectgradationtasktypeDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public void rebindTaskType(String id, LoginUser currentUser) {
		projectgradationtasktypeDaoImpl.deleteEntity(projectgradationtasktypeDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public void moveTreeNode(String ids, String targetId, LoginUser currentUser) {
		String[] idArray = ids.split(",");
		ProjectGradation target = getProjectgradationEntity(targetId);
		if (target != null && target.getModel().equals("1")) {
			throw new RuntimeException("'类型'节点下禁止创建子节点!");
		}
		for (int i = 0; i < idArray.length; i++) {
			// 移动节点
			ProjectGradation node = getProjectgradationEntity(idArray[i]);
			if (target != null && target.getTreecode().indexOf(node.getTreecode()) >= 0) {
				throw new RuntimeException("不能够移动到其子节点下!");
			}
			if (target == null) {
				node.setParentid("NONE");
			} else {
				node.setParentid(targetId);
			}
			projectgradationDaoImpl.editEntity(node);
			// 构造所有树TREECODE
			List<ProjectGradation> list = projectgradationDaoImpl.getAllSubNodes(idArray[i]);
			for (ProjectGradation org : list) {
				initTreeCode(org.getId());
			}
		}

	}

	@Override
	@Transactional
	public List<ProjectGradation> getGradationsByTypeid(String projectTypeid) {
		ProjectType type = projecttypeDaoImpl.getEntity(projectTypeid);
		if (type == null) {
			throw new RuntimeException("未找到该项目");
		}
		if (!type.getModel().equals("1")) {
			throw new RuntimeException("该分類非项目类型，可能是一个项目分类");
		}
		if (!type.getPstate().equals("1")) {
			throw new RuntimeException("该项目状态不可用");
		}
		List<ProjectGradation> gradations = new ArrayList<>();
		List<ProjectTypeGradation> res = projecttypegradationDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTTYPEID", projectTypeid, "=")).toList());
		Collections.sort(res, new Comparator<ProjectTypeGradation>() {
			@Override
			public int compare(ProjectTypeGradation o1, ProjectTypeGradation o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		for (ProjectTypeGradation re : res) {
			ProjectGradation gardation = projectgradationDaoImpl.getEntity(re.getGradationid());
			if (gardation.getModel().equals("1") && gardation.getPstate().equals("1")) {
				gradations.add(gardation);
			}
		}
		if (gradations.size() <= 0) {
			throw new RuntimeException("该项目暂无可用阶段");
		}
		return gradations;
	}

	@Override
	@Transactional
	public List<TaskType> getTaskTypes(String gradationid) {
		ProjectGradation gradation= 	projectgradationDaoImpl.getEntity(gradationid);
		if (gradation == null) {
			throw new RuntimeException("未找到该项目阶段");
		}
		if (!gradation.getModel().equals("1")) {
			throw new RuntimeException("该项目阶段非阶段类型，可能是一个阶段分类");
		}
		if (!gradation.getPstate().equals("1")) {
			throw new RuntimeException("该阶段状态不可用");
		}
		List<TaskType> taskTypes = new ArrayList<>();
		List<ProjectGradationTasktype> res = projectgradationtasktypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("GRADATIONID", gradationid, "=")).toList());
		
		for (ProjectGradationTasktype re : res) {
			TaskType taskType = tasktypeDaoImpl.getEntity(re.getTasktypeid());
			if (taskType.getModel().equals("1") && taskType.getPstate().equals("1")) {
				taskTypes.add(taskType);
			}
		}
		if (taskTypes.size() <= 0) {
			throw new RuntimeException("该项目暂无可用任務類型");
		}
		Collections.sort(taskTypes, new Comparator<TaskType>() {
			@Override
			public int compare(TaskType o1, TaskType o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return taskTypes;
	}

}
